<template>
  <v-app>
    <v-app-bar app elevation="4">
      <img src="../assets/points.png" height="56" width="198" style="margin-right: 30px"/>
      <v-btn color="error" @click="cleanStorage" v-if="debug">
        clear sessionStorage and indexedDB
      </v-btn>
    </v-app-bar>
    <!-- 根据应用组件来调整你的内容 -->
    <v-main id="main">
      <!-- 给应用提供合适的间距 -->
      <v-container fluid>
        <v-row>
          <!-- 工具栏 -->
          <v-col cols="3" id="col">
            <!-- tools -->
            <v-card
              elevation="10"
              class="mx-auto my-12"
              max-width="374"
              id="toolBar">
              <v-card-title>predict</v-card-title>

              <v-card-text>
                <v-row
                  align="center"
                  class="mx-0"
                >
                  this is semantic segmentation tool bar
                </v-row>
              </v-card-text>

              <v-divider class="mx-4"></v-divider>
              <!-- 选择模型，上传文件 -->
              <v-card-text>
                <v-form>
                  <v-select :items="models" label="model" @change="handelSelectChange"></v-select>
                  <v-file-input accept=".txt" label="file" show-size v-model="file" @change="uploadFile"></v-file-input>
                  <v-btn
                    :loading="loading"
                    :disabled="loading"
                    block
                    @click="postFile"
                  >
                    predict now
                    <v-icon>mdi-play</v-icon>
                  </v-btn>
                </v-form>
              </v-card-text>
              <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn plain color="orange">
                  <v-icon>mdi-menu-right-outline</v-icon>
                </v-btn>
              </v-card-actions>
            </v-card>
            <!-- files -->
            <v-card
              elevation="10"
              class="mx-auto my-12"
              max-width="374"
              :max-height="cardMaxH">
              <v-card-title>files</v-card-title>

              <v-card-text>
                <v-row
                  align="center"
                  class="mx-0"
                >
                  open files
                </v-row>
              </v-card-text>

              <v-divider class="mx-4"></v-divider>

              <v-card-text>
                <v-list :max-height="listMaxH" id="fileList">
                  <v-list-item-group
                    v-model="selectedItem">
                    <v-list-item
                      v-for="(item, i) in items"
                      :key="i">
                      <v-list-item-content>
                        <v-list-item-title v-text="item.name"></v-list-item-title>
                      </v-list-item-content>
                      <v-list-item-action>
                        <v-btn icon color="error" small @click="deleteItem(i, item.id)">
                          <v-icon>mdi-trash-can-outline</v-icon>
                        </v-btn>
                      </v-list-item-action>
                      <v-list-item-action>
                        <v-btn icon color="success" small @click="renderItem(i, item.id)">
                          <v-icon>mdi-play-outline</v-icon>
                        </v-btn>
                      </v-list-item-action>
                      <v-list-item-action>
                        <v-btn icon color="success" small @click="downloadFile(item.id)">
                          <v-icon>mdi-download-outline</v-icon>
                        </v-btn>
                      </v-list-item-action>
                    </v-list-item>
                  </v-list-item-group>
                </v-list>
              </v-card-text>
            </v-card>
          </v-col>
          <!-- 3d -->
          <v-col>
            <Render ref="renderBox" @setLoadingTrue="setLoadingTrue" @setLoadingFalse="setLoadingFalse"></Render>
          </v-col>
        </v-row>
      </v-container>
    </v-main>
  </v-app>
</template>

<script>
  import {uploadFile} from '../api/index'
  import IndexDBWrapper from 'indexdbwrapper'
  // eslint-disable-next-line no-unused-vars
  import Render from './Render'

  export default {
    // eslint-disable-next-line vue/multi-word-component-names
    name: 'Index',
    // eslint-disable-next-line vue/no-unused-components
    components: {Render},
    data() {
      return {
        models: ['indoor_3d'],
        selected: false,        // 是否选择模型
        cardMaxH: 200,
        listMaxH: 200,
        file: null,
        uploaded: false,        // 是否上传文件
        db: null,
        loading: false,
        items: [],
        selectedItem: 0
      }
    },
    beforeMount() {
      // 创建indexDB
      if (this.db == null) {
        const db = new IndexDBWrapper('db', 1, {
          onupgradeneeded(e) {
            const innerDb = e.target.result
            console.log('index innerDb', innerDb)
            // 如果不存在t1表则创建e
            console.log('t1不存在', !innerDb.objectStoreNames.contains('t1'))
            if (!innerDb.objectStoreNames.contains('t1')) {
              // 创建表
              innerDb.createObjectStore('t1', {
                autoIncrement: false, // 自增
                keyPath: 'id'         // 主键
              })
            }
          }
        })
        this.db = db
        console.log('index db link', this.db)
      }
    },
    mounted() {
      let main = document.getElementById('main')
      console.log('main.offsetHeight', main.offsetHeight)
      // 设置渲染器的高度
      window.sessionStorage.setItem('renderHeight', main.offsetHeight - 88)
      // 设置卡片最大高度
      let col = document.getElementById('col')
      let toolBar = document.getElementById('toolBar')
      this.cardMaxH = col.offsetHeight - toolBar.offsetHeight + 20
      // 设置list最大高度
      this.listMaxH = this.cardMaxH - 100
      // 唯一id
      if (window.sessionStorage.getItem('id') == null) {
        window.sessionStorage.setItem('id', 0)
      }
      // 存储items、selectedItem
      if (window.sessionStorage.getItem('items') == null) {
        window.sessionStorage.setItem('items', JSON.stringify(this.items))
        window.sessionStorage.setItem('selectedItem', this.selectedItem)
      } else {
        this.items = JSON.parse(window.sessionStorage.getItem('items'))
        this.selectedItem = JSON.parse(window.sessionStorage.getItem('selectedItem'))
      }
    },
    methods: {
      cleanStorage() {
        window.sessionStorage.clear()
        let that = this
        if (that.db != null) {
          that.db.open()
          that.db.clear('t1')
            .then(() => {
              that.$message.success('t1表清空成功')
              that.db.close()
            })
            .catch(err => {
              that.$message.error('t1表清空失败' + err)
              that.db.close()
            })
        }
      },
      deleteItem(i, id) {
        console.log('click item index', i)
        console.log('click item id', id)
        // 删除items中对应item
        this.items.splice(i, 1)
        window.sessionStorage.setItem('items', JSON.stringify(this.items))

        // 删除indexDB中对应的行
        let that = this
        if (that.db != null) {
          console.log('before delete current db', that.db)
          that.db.open()
          that.db.delete('t1', id)
            .then(res => {
              console.log('delete res', res)
              that.db.close()
            })
            .catch(err => {
              console.log('delete err', err)
              that.db.close()
            })
        } else {
          that.$message.error('数据库连接为null！')
        }
      },
      renderItem(i, id) {
        console.log('click item id', id)
        let renderBox = this.$refs.renderBox
        renderBox.createPoints(i, id)
      },
      handelSelectChange() {
        this.selected = true
      },
      postFile() {
        if (this.uploaded && this.selected && this.items.length <= 10) {
          let that = this
          let reader = new FileReader()
          // 上传txt文件
          reader.readAsText(that.file)
          // readAsBinaryString：该方法将文件读取为二进制字符串，通常我们将它传送到后端，后端可以通过这段字符串存储文件。
          reader.onload = function() {
            let id = window.sessionStorage.getItem('id')
            let data = {
              id: id++,
              name: that.file.name,
              data: this.result
            }
            window.sessionStorage.setItem('id', id)
            that.loading = true
            that.$message.warning('文件上传中')
            uploadFile(data)
              .then(res => {
                // createList
                console.log(res)
                // 1.添加list和设置选择的item
                that.items.push({
                  id: res.id,
                  name: res.name
                })
                console.log('push a item', that.items)
                that.selectedItem = that.items.length - 1
                window.sessionStorage.setItem('items', JSON.stringify(that.items))
                window.sessionStorage.setItem('selectedItem', that.selectedItem)
                // 2.将res存入indexedDB
                if (that.db != null) {
                  that.db.open()
                  that.db.add('t1', res)
                    .then(res => {
                      console.log('add res res', res)
                      that.db.close()
                      console.log('add db after close', that.db)
                    })
                    .catch(err => {
                      console.log('add res err', err)
                      that.db.close()
                      console.log('add db after close', that.db)
                    })
                }
                // render
                // that.$refs.renderBox.createPoints(that.selectedItem, res.id)
                that.loading = false
              })
              .catch(err => {
                that.$message.error('文件上传失败' + err)
                console.log('postFile err', err)
                that.loading = false
              })
          }
        } else {
          if (!this.uploaded) {
            this.$message.error('请检查文件上传！')
          } else if(!this.selected) {
            this.$message.error('请选择模型！')
          } else {
            this.$message.error('超出上传文件数量！')
          }
        }
      },
      uploadFile(file) {
        this.uploaded = file != null
      },
      downloadFile(id) {
        let that = this
        that.db.open()
        that.db.get('t1', id)
          .then(res => {
            let text = ''
            let arr_pred = res.arr_pred
            let row_length = arr_pred[0].length
            let row_max_index = row_length - 1
            for (let i = 0; i < arr_pred.length; i++) {
              for (let j = 0; j < row_length; j++) {
                if (j === row_max_index) {
                  text += arr_pred[i][j] + '\n'
                } else {
                  text += arr_pred[i][j] + ' '
                }
              }
            }
            // console.log('download txt', text)

            let file_name = res.name
            console.log('file name original', file_name)
            file_name = file_name.replace('.txt', '_pred.txt')
            console.log('pred file name', file_name)
            let element = document.createElement('a')
            element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text))
            element.setAttribute('download', file_name)
            element.style.display = 'none'
            document.body.appendChild(element)
            element.click()
            document.body.removeChild(element)
          })
          .catch(err => {
            that.$message.error('下载文件错误 ', err)
          })
      }
    }
  }
</script>

<style scoped>
  #fileList {
    overflow-y: scroll;
  }
</style>
